require 'zip/zip'
require 'zip/zipfilesystem'
require 'iconv'

class Project < ActiveRecord::Base
  belongs_to :project_type
  has_many :components

  def project_url_root
    "/project/#{self.id}"
  end

  def project_root 
    path = "#{RAILS_ROOT}/public" + project_url_root
    FileUtils.mkdir_p(path) unless File.exist?(path)
    path
  end

  def generate_zip
    zip_file = "#{project_root}/#{self.name}.zip"
    File.delete(zip_file) if File.exists?(zip_file)
    Zip::ZipFile.open(zip_file, Zip::ZipFile::CREATE) do |zip|
      zip_add zip, generate_project_file
      zip_add zip, project_type.base_file, "base.ppt"
      com_index = 0
      components.each do |com|
        com_index += 1
        zip_add zip, com.template.filename, "#{com_index}.pot" if com.template
        img_index = 0
        com.images.each do |img| 
          img_index += 1
          zip_add zip, img.filename, image_filename(com_index, img_index, img.filename)
        end
      end
    end
    File.chmod(0755, zip_file)
    zip_file
  end

  private
  def zip_add(zip, source_file, new_name=nil)
    new_name ||= File.basename(source_file)
    zip.add new_name, source_file
  end

  LINE_BREAK = "\r\n"

  def to_win(str)
    #Iconv.iconv('UTF-8', 'gb18030', str)
    str.to_s.gsub("\n", LINE_BREAK)
  end

  def generate_project_file
    project_file = "#{project_root}/project.txt"
    project_file_utf8 = "#{project_root}/project.utf8.txt"
    File.open(project_file_utf8, 'w') do |file|
      #file.write "\xEF\xBB\xBF"  # unicode file header
      file.write "components: #{components.count}" + LINE_BREAK
      file.write "lead_pages: #{project_type.lead_pages}" + LINE_BREAK
      file.write LINE_BREAK

      com_index = 0
      components.each do |component|
        com_index += 1
        img_index = 0

        file.write "[#{to_win(component.name)}]" + LINE_BREAK
        file.write "template: #{com_index}.pot" + LINE_BREAK if component.template
        file.write "resources: #{component.images.collect{|img| img_index += 1; image_filename(com_index, img_index, img.filename)}.join(',')}" + LINE_BREAK if component.images
        file.write "title: #{to_win(component.title)}" + LINE_BREAK
        logger.debug "component.title.length =========== #{component.title.length}"
        file.write "body: #{to_win(component.body)}" + LINE_BREAK
      end
    end

    `iconv -f utf-8 -t gb18030 #{project_file_utf8} > #{project_file}`
    project_file
  end

  def image_filename(com_index, img_index, filename)
    com_index.to_s + "_" + img_index.to_s + filename[-4, 4]
  end

  # active_scaffold callbacks: authorized_for_crud
  public
  def authorized_for_create?
    true
  end

  def authorized_for_read?
    true
  end

  def authorized_for_update?
    true
  end

  def authorized_for_destroy?
    true
  end

  # human names
  ModelName = "项目"
  ColumnNames ={
    :name => "名称",
    :project_type => "项目类型",
    :components => "组成部分"
  }
end
